<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :rules="rules" :model="form">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>

    </el-form>

  </div>
</template>
<script>
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default ({
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: { type: Boolean, required: false }
  },
  data() {
    const validCode = (rule, value, callback) => {
      let codeList = []
      // value就是当前用户输入的编码它不能与现在的originlist重复
      // 如果重复验证就不通过，if(value能与现有的编码数据（originList）重复) {
      // 1. 从originList（[{id, pid,name, code},{id, pid,name, code}]）中找出全部的编码数据
      if (this.isEdit) {
        const arr = this.originList.filter(item => item.id !== this.id)
        // 把当前正在编辑的部门编号（this.id）排除在外
        // 过滤掉当前的部门，map的到部门编号列表
        codeList = arr.map(item => item.code)
      } else {
      // 添加
        codeList = this.originList.map(item => item.code)
      }
      console.log('要校验的部门编号', value, codeList)
      codeList.includes(value) ? callback(new Error(value + ' 已经被占用')) : callback()
    }
    const validateName = (rule, value, callback) => {
      let nameList = []
      if (this.isEdit) {
        // 找到当前编辑的元素的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 根据pid找兄弟们不包括自己
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
        console.log('编辑', nameList)
      } else {
        // 添加部门，value在统计部门下不重复
        // 找出所占用的name
        nameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
        console.log(nameList)
      }
      // 2. 如果nameList中包含value，校验不通过
      nameList.includes(value) ? callback(new Error(value + '已经占用')) : callback()
    }
    return {
      employees: [],
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-300个字符', trigger: 'blur' }
        ]
        // rule当前的规则 value被校验的值 callback回调如果通过了校验直接调用callback()如果没有调用callback(错误对象，说明原因)callback(new Error('错误说明'))

      }
    }
  },
  // watch: {
  //   id(newVal, oldVal) {
  //     if (newVal) {
  //       console.log(newVal, oldVal)
  //       // 重发请求获取详情、
  //       this.loadDetail()
  //     }
  //   }
  // },
  created() {
    // this.loadEmployee()
    this.loadDetail()
    // 如果isedit为true当前是编辑
    if (this.isedit) {
      this.loadEmployee()
    }
    // this.loadEmployee()
  },
  methods: {
    async loadEmployee() {
      const res = await getEmployeeSimple(this.id)
      console.log('loadEmployee', res)
      this.employees = res.data
    },
    // 执行具体的添加动作
    async doAdd() {
      // 去获取pid：当前要添加的部门所在的父级的id
      // 从props中获取
      // 组件参数
      const params = { ...this.form, pid: this.id }
      console.log(params)
      // 调用接口
      const res = await addDepartments(params)
      console.log(res)
      // 通知父组件关闭弹层，再次更新数据
      this.$emit('update-depart')
    },
    // 获取当前部门的详情
    async loadDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.id)
        this.form = res.data
        console.log('现在是编辑', res)
      }
    },
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        console.log(res)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('update-depart')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    // 确认
    hSubmit() {
      // 表单验证
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 取消
    hCancel() {
      // 抛出事件通知父组件关闭弹层
      this.$emit('close')
    },
    resetForm() {
      // 重置表单数据
      // 清空校验结果
      this.$refs.deptForm.resetFields()
    }

  }

})
</script>

